/**
 * Copyright (c) 华南农业大学信息学院蔡超敏2015版权所有
 * 
 * 文件创建时间：2015年5月3日
 */
package org.scauinfo.fpos.action.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import org.scauinfo.fpos.action.BaseAction;
import org.scauinfo.fpos.model.MemberModel;
import org.scauinfo.fpos.model.SaleorderModel;
import org.scauinfo.fpos.model.SaleorderitemModel;
import org.scauinfo.fpos.service.MemberService;
import org.scauinfo.fpos.service.ProductService;
import org.scauinfo.fpos.service.SaleorderService;
import org.scauinfo.fpos.service.SaleorderitemService;
import org.scauinfo.fpos.service.TableplateService;
import org.scauinfo.fpos.service.UserService;
import org.scauinfo.fpos.util.ExceptionUtil;
import org.scauinfo.fpos.util.Json;
import org.scauinfo.fpos.vo.Member;
import org.scauinfo.fpos.vo.Product;
import org.scauinfo.fpos.vo.Saleorder;
import org.scauinfo.fpos.vo.Saleorderitem;
import org.scauinfo.fpos.vo.Tableplate;
import org.scauinfo.fpos.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author 蔡超敏
 * 
 */
@Namespace("/")
@Scope("prototype")
@Controller
@Action(value = "saleorder", results = { @Result(name = "success", location = "/monthReport.jsp") })
@RemoteProxy(name = "saleorderAction")
public class SaleorderAction extends BaseAction implements
		ModelDriven<Saleorder> {

	private static final long serialVersionUID = 3088843221530537631L;
	private static final Logger logger = Logger
			.getLogger(SaleorderAction.class);
	@Autowired
	private SaleorderService saleorderService;

	@Autowired
	private SaleorderitemService saleorderitemService;
	@Autowired
	private ProductService productService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private UserService userService;

	@Autowired
	private TableplateService tableplateService;

	public Member member = new Member();
	public User user = new User();
	public Saleorder saleorder = new Saleorder(member, user);

	public String memberId;
	public String begindate;
	public String enddate;

	public String showMonthReport() {
		try {
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();

			int year = Integer.parseInt(ServletActionContext.getRequest()
					.getParameter("year").toString());
			System.out.println("年是: " + year);

			for (int i = 1; i <= 11; i++) {
				List<Saleorder> saleorders = saleorderService.findAllSaleorder(
						null, String.format("%d-%d-01", year, i),
						String.format("%d-%d-01", year, i + 1));
				double amount = 0;
				for (Iterator iterator = saleorders.iterator(); iterator
						.hasNext();) {
					Saleorder saleorder = (Saleorder) iterator.next();
					amount += saleorder.getRealIncome();
				}
				dataset.setValue(amount, "盈利金额", i + "月份");
			}

			List<Saleorder> saleorders = saleorderService.findAllSaleorder(
					null, String.format("%d-12-01", year),
					String.format("%d-01-01", year + 1));
			double amount = 0;
			for (Iterator iterator = saleorders.iterator(); iterator.hasNext();) {
				Saleorder saleorder = (Saleorder) iterator.next();
				amount += saleorder.getRealIncome();
			}
			dataset.setValue(amount, "盈利金额", 12 + "月份");

			JFreeChart chart = ChartFactory.createBarChart3D("销售统计图", "数值",
					"时间", dataset, PlotOrientation.VERTICAL, true, true, false);
			CategoryPlot plot = (CategoryPlot) chart.getPlot();
			// 背景色　透明度
			plot.setBackgroundAlpha(0.5f);
			// 前景色　透明度
			plot.setForegroundAlpha(0.5f);
			BarRenderer3D renderer = new BarRenderer3D();
			renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
			renderer.setBaseItemLabelsVisible(true);
			// 默认的数字显示在柱子中，通过以下两句调整数字的显示
			// 注意，此句很关键，若无此句，那数字的显示会覆盖，给人数字没有显示出来的问题
			renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
					ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
			renderer.setItemLabelAnchorOffset(10D);
			// 设置每个地区所包含的平行柱的之间的距离
			// renderer.setItemMargin(0.3);
			plot.setRenderer(renderer);

			chart.setBackgroundPaint(ChartColor.WHITE);
			CategoryPlot p = chart.getCategoryPlot();
			// 设置图的背景颜色
			p.setBackgroundPaint(ChartColor.WHITE);
			ServletContext s1 = ServletActionContext.getServletContext();
			String temp = s1.getRealPath("/");
			System.out.println(temp);
			File path = new File(temp + "report");
			path.mkdir();

			String url = temp + "report/"
					+ ServletActionContext.getRequest().getSession().getId()
					+ ".jpeg";
			File file = new File(url);

			Map request = (Map) ActionContext.getContext().get("request");
			request.put("imgReport", "./report/"
					+ ServletActionContext.getRequest().getSession().getId()
					+ ".jpeg");

			try {
				ChartUtilities.saveChartAsPNG(file, chart, 800, 500);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("操作失误");
		}
		return "success";

	}

	@RemoteMethod
	public String ensureMember(String memberId) {
		Map<String, Object> session = ActionContext.getContext().getSession();

		Member member = memberService.find(memberId);
		session.put("saleorder", null);
		if (member == null) {
			return null;
		}

		session.put("member", member);

		List<MemberModel> mList = new ArrayList<MemberModel>();

		MemberModel memberModel = new MemberModel(member.getId(),
				member.getMemberId(), member.getName());
		memberModel.setGender(member.getGender());
		memberModel.setAddress(member.getAddress());
		memberModel.setTelephone(member.getTelephone());
		memberModel.setMpermissionName(member.getMemberpermission()
				.getMpermissionName());

		mList.add(memberModel);
		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("member", mList);
		String json = JSON.toJSONString(maps);
		System.out.println("ensureMember-----------" + json);
		return json;
	}

	@RemoteMethod
	public String endNewSale(Integer id) {
		Json result = new Json();
		Map<String, Object> session = ActionContext.getContext().getSession();
		System.out.println("tags ----Saleorder" + saleorder.getId());
		try {
			Tableplate tableplate = tableplateService.get(id);

			Saleorder saleorder = (Saleorder) session.get("saleorder");

			saleorder.setTableplate(tableplate);

			saleorderService.saveSaleorder(saleorder);

			tableplate.setTableState(1);

			tableplateService.updateTableplate(tableplate);

			session.put("saleorder", null);
			session.put("member", null);
			result.setSuccess(true);
			result.setMsg("添加订单成功");
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("添加订单失败");
		}
		return "success";
	}

	@RemoteMethod
	public String beginNewSale() {

		Map<String, Object> session = ActionContext.getContext().getSession();

		session.put("saleorder", null);

		User user = (User) session.get("user");
		Member member = (Member) session.get("member");

		if (member == null) {
			member = memberService.get(9);
		}

		Saleorder saleorder = new Saleorder(member, user);

		saleorder.setCreatedDatetime(new Timestamp(System.currentTimeMillis()));

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyyMMddHHmmssSSS");
		String saleorderId = simpleDateFormat.format(new Date(System
				.currentTimeMillis())) + member.getMemberId();

		System.out.println(saleorderId);

		saleorder.setSaleorderId(saleorderId);

		saleorder.setState(0);
		saleorder.setTableplate(tableplateService.get(1));
		session.put("saleorder", saleorder);

		return saleorderId;
	}

	@RemoteMethod
	public String addProductItem(Integer id) {
		Map<String, Object> session = ActionContext.getContext().getSession();

		Saleorder saleorder = (Saleorder) session.get("saleorder");
		if (saleorder == null) {
			saleorder = new Saleorder();
		}

		Member member = (Member) session.get("member");

		Product aproduct = productService.get(id);

		boolean flag = false;
		double amount = 0;
		for (Iterator iterator = saleorder.getSaleorderitems().iterator(); iterator
				.hasNext();) {
			Saleorderitem saleorderitem = (Saleorderitem) iterator.next();
			if (aproduct.getId() == saleorderitem.getProduct().getId()) {
				saleorderitem.setCount(saleorderitem.getCount() + 1);
				flag = true;
			}

			amount += saleorderitem.getProduct().getProductPrice()
					* saleorderitem.getCount();
		}

		if (!flag) {
			Saleorderitem saleorderitem = new Saleorderitem();
			saleorderitem.setSaleorder((Saleorder) session.get("saleorder"));
			saleorderitem.setCount(1);
			saleorderitem.setProduct(aproduct);
			saleorderitem.setState(0);

			saleorder.getSaleorderitems().add(saleorderitem);

			amount += aproduct.getProductPrice();
		}

		String rule = "";
		double ddiscount=10;
		if (member != null) {
			rule = member.getMemberpermission().getMrules();
			 ddiscount = Double.parseDouble(rule.trim());

			System.out.println("ddiscount" + ddiscount);
		} else {
			rule = "";
		}

		double realIncome = amount * ddiscount / 10;
		double discount = realIncome - amount;

		String json = "{\"salemoney\": [{ \"amount\":"
				+ String.format("%.2f", amount) + ",\"discount\":"
				+ String.format("%.2f", discount) + ",\"realIncome\":"
				+ String.format("%.2f", realIncome) + "}]}";

		System.out.println("returnSaleMoney json" + json);

		saleorder.setRealIncome(realIncome);

		session.put("saleorder", saleorder);
		return json;
	}

	@RemoteMethod
	public String returnSaleMoney() {
		System.out.println("returnSaleMoney 1");
		Map<String, Object> session = ActionContext.getContext().getSession();

		Saleorder saleorder = (Saleorder) session.get("saleorder");
		Member member = (Member) session.get("member");

		if (saleorder == null) {
			return null;
		}
		double amount = 0;
		for (Iterator iterator = saleorder.getSaleorderitems().iterator(); iterator
				.hasNext();) {
			Saleorderitem saleorderitem = (Saleorderitem) iterator.next();
			amount += saleorderitem.getProduct().getProductPrice()
					* saleorderitem.getCount();
		}
		String rule = "";
		if (member != null)
			rule = member.getMemberpermission().getMrules();
		else {
			rule = "";
		}

		double discount = amount * 0.9;

		double realIncome = amount - discount;

		String json = "{\"salemoney\": [{ \"amount\":" + amount
				+ ",\"discount\":" + discount + ",\"realIncome\":" + realIncome
				+ "}]}";

		System.out.println("returnSaleMoney json" + json);
		return json;
	}

	/**
	 * 得到数据列表
	 */
	public void getSaleorderitems() {
		Map<String, Object> session = ActionContext.getContext().getSession();

		Saleorder saleorder = (Saleorder) session.get("saleorder");

		if (saleorder == null) {
			System.out.println("SaleorderActiongrid ----null");
			saleorder = new Saleorder();
		}

		int total = saleorder.getSaleorderitems().size();
		System.out.println("SaleorderActiongrid ----total" + total + "page"
				+ page + "rows" + rows + ", sort" + sort + ", order" + order);
		List<SaleorderitemModel> list = new ArrayList<SaleorderitemModel>();
		for (Iterator iterator = saleorder.getSaleorderitems().iterator(); iterator
				.hasNext();) {
			Saleorderitem saleorderitem = (Saleorderitem) iterator.next();
			SaleorderitemModel saleorderitemModel = new SaleorderitemModel(
					saleorderitem.getId(), saleorderitem.getProduct()
							.getProductId(), saleorderitem.getProduct()
							.getProductName(), saleorderitem.getProduct()
							.getProductPrice(), null, null, null, null,
					saleorderitem.getCount(), saleorderitem.getProduct()
							.getDescription());

			saleorderitemModel.setState(saleorderitem.getState());

			list.add(saleorderitemModel);
		}
		System.out.println("SaleorderActiongrid ----end" + list.size());
		writeJson(total, list);
	}

	/**
	 * 得到数据列表
	 */
	public void grid() {

		System.out.println("saleordergrid ----memberId" + memberId);
		System.out.println("saleordergrid ----begindate" + begindate);
		System.out.println("saleordergrid ----enddate" + enddate);

		System.out.println("saleordergrid ----1");
		int total = saleorderService.findAllSaleorder(memberId, begindate,
				enddate).size();
		System.out.println("saleordergrid ----total" + total + "page" + page
				+ "rows" + rows + ", sort" + sort + ", order" + order);

		List<Saleorder> list = saleorderService.findAllSaleorder(memberId,
				begindate, enddate, page, rows, sort, order);
		System.out.println("saleordergrid ----2" + list.size());

		List<SaleorderModel> mList = new ArrayList<SaleorderModel>();

		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Saleorder saleorder = (Saleorder) iterator.next();
			SaleorderModel saleorderModel = new SaleorderModel(
					saleorder.getId(), saleorder.getMember().getMemberId(),
					saleorder.getMember().getName(), saleorder.getMember()
							.getAddress(), saleorder.getUser().getUserId(),
					saleorder.getUser().getUserId(), saleorder.getUser()
							.getAccount(), saleorder.getSaleorderId(),
					saleorder.getCreatedDatetime(), saleorder.getState(),
					saleorder.getDescription());

			saleorderModel.setRealIncome(saleorder.getRealIncome());
			saleorderModel.setTablePlate(saleorder.getTableplate()
					.getTablePlate());

			switch (saleorderModel.getState()) {
			case 0:
				saleorderModel.setStateStr("可退单");
				break;
			case 1:
				saleorderModel.setStateStr("不可退单");
				break;
			case 2:
				saleorderModel.setStateStr("已付款");
				break;
			}

			// 时间格式
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy/MM/dd HH:mm:ss");
			String datetime = simpleDateFormat.format(saleorder
					.getCreatedDatetime());

			saleorderModel.setCreatedDatetimeStr(datetime);

			mList.add(saleorderModel);
		}
		System.out.println("saleordergrid ----mListsize" + mList.size());
		writeJson(total, mList);
	}

	/**
	 * 添加操作
	 */
	public void add() {
		Json result = new Json();

		System.out.println("tags ----Saleorder" + saleorder.getId());
		try {
			saleorder.setMember(memberService
					.get(saleorder.getMember().getId()));
			saleorder.setUser(userService.get(saleorder.getUser().getId()));

			saleorderService.saveSaleorder(saleorder);
			result.setSuccess(true);
			result.setMsg("添加订单成功");
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("添加订单失败");
		}
		writeJson(result);
	}

	/**
	 * 修改操作
	 */
	public void edit() {
		Json result = new Json();
		try {
			saleorder.setMember(memberService
					.get(saleorder.getMember().getId()));
			saleorder.setUser(userService.get(saleorder.getUser().getId()));

			saleorderService.saveSaleorder(saleorder);
			result.setSuccess(true);
			result.setMsg("修改订单成功");
			result.setSuccess(true);
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("修改订单失败");
		}
		writeJson(result);
	}

	/**
	 * 删除操作
	 */
	public void remove() {
		Json result = new Json();
		try {
			System.out.println("tags ----=" + saleorder.getId());
			saleorderService.deleteSaleorder(saleorder.getId());
			result.setSuccess(true);
			result.setMsg("删除订单成功");
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("删除订单失败");
		}
		writeJson(result);
	}

	@Override
	public Saleorder getModel() {
		return saleorder;
	}

	/**
	 * @return the memberId
	 */
	public String getMemberId() {
		return memberId;
	}

	/**
	 * @param memberId
	 *            the memberId to set
	 */
	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	/**
	 * @return the begindate
	 */
	public String getBegindate() {
		return begindate;
	}

	/**
	 * @param begindate
	 *            the begindate to set
	 */
	public void setBegindate(String begindate) {
		this.begindate = begindate;
	}

	/**
	 * @return the enddate
	 */
	public String getEnddate() {
		return enddate;
	}

	/**
	 * @param enddate
	 *            the enddate to set
	 */
	public void setEnddate(String enddate) {
		this.enddate = enddate;
	}

}